<template>
  <div class="management-tab">
    <el-form ref="form" :model="formData" inline label-position="top" :rules="rules" :show-message="false">
      <el-form-item :label="item.label" :prop="item.prop" v-for="item in formItems" :key="item.prop">
        <span slot="label">
          {{item.label}}
          <i class="el-icon-search"></i>
        </span>
        <el-select v-model="formData[item.prop]" style="width: 122px" clearable filterable placeholder="">
          <el-option v-for="option in app.dataset[item.options]" :key="option" :label="option" :value="option"></el-option>
        </el-select>
      </el-form-item>
        <!-- 机芯基本属性 -->
        <el-form-item label="item.prop" :prop="item.prop" v-for="(item,index) in myProperties" :key="item.prop">
          <span slot="label">
            <span>属性~{{index+1}}</span>
            <i class="el-icon-delete" @click="removeProp(index)"></i>
          </span>
          <el-select :value="item.prop" style="width: 122px" clearable @change="onPropChange($event, item)" filterable placeholder="">
            <el-option v-for="option in properties(index)" :key="option" :label="option" :value="option"></el-option>
          </el-select>
          <el-input-number v-if="item.prop" v-model="formData[item.prop]" :controls="false" :min="0" :max="200" style="width: 74px"></el-input-number>
        </el-form-item>

        <el-form-item label="特殊属性" v-if="myProperties.length < 4">
          <el-button type="primary" icon="el-icon-plus" @click="addProp">属性</el-button>
        </el-form-item>
    </el-form>
    <div>
      <el-button type="primary" @click="onSave" icon="el-icon-plus">保存/{{formData.id ? '编辑' : '添加'}}</el-button>
      <el-button type="primary" @click="onReset" icon='el-icon-refresh'>清空{{formData.id?'/撤消编辑' : ''}}</el-button>
      <el-button type="primary" @click="removeAll" icon="el-icon-delete">删除所有机芯</el-button>
      <el-popover
        placement="right"
        width="400"
        trigger="click">
        <el-alert
          title="复制以下文本内容，保存到本地文件中。"
          type="info"
          :closable="false"
          effect="dark">
        </el-alert>
        <el-input style="margin-top: 10px" readonly :value="exportData" :rows="8" type="textarea"></el-input>
        <el-button style="margin-left: 10px" slot="reference" type="primary">导出</el-button>
      </el-popover>
      <el-popover
        placement="right"
        width="400"
        trigger="click">
        <el-alert
          title="复制机芯文本内容到文本框中。"
          type="info"
          :closable="false"
          effect="dark">
        </el-alert>
        <el-input style="margin-top: 10px" v-model="importData" :rows="8" type="textarea"></el-input>
        <div style="text-align: center; margin-top: 10px">
          <el-button type="primary" @click="onImport">导入/覆盖已有机芯</el-button>
        </div>
        <el-button slot="reference" type="primary">导入</el-button>
      </el-popover>
      <el-badge :value="data.length" :hidden="!data.length" type="primary">
        <el-button type="primary" @click="onSearch" icon="el-icon-search">查询</el-button>
      </el-badge>
    </div>

    <div class="movement-list">
      <el-empty v-if="!data.length"></el-empty>
      <el-card class="movement-card" :class="{'card-edit': formData.id === item.id}" v-for="(item) in data" :key="item.id">
        <div>
          <h4>
            {{item.name}}
            <el-tag v-if="item.season" effect="dark" size="mini" type="primary">{{item.season}}</el-tag>
            <span  style="float:right; cursor: pointer" v-if="formData.id !== item.id">
              <i class="el-icon-edit" @click="initEdit(item)"></i>
              <i  class="el-icon-delete" @click="remove(item)"></i>
            </span>
          </h4>
        </div>
        <p><span>{{'⧫'.repeat(item.star || 0)}}</span><span>{{item.direction}}</span></p>
        <div>
          <h4>{{item.mainProp}}</h4>
        </div>
        <template v-for="prop in app.dataset.properties">
          <p class="prop" :class="{light: !item[prop]}" v-if="item[prop]" :key="prop">
            <span>{{prop}}：</span>
            <span>{{item[prop] || 0}}</span>
          </p>
        </template>
      </el-card>
    </div>
  </div>
</template>

<script>
module.exports = {
  inject: ["app"],
  data() {
    return {
      formData: {},
      rules: {
        name: { required: true, message: "请选择机芯", trigger: "change" },
        star: { required: true, message: "请选择星级", trigger: "change" },
        mainProp: {
          required: true,
          message: "请选择基本属性",
          trigger: "change",
        },
        direction: {
          required: true,
          message: "请选择机芯位置",
          trigger: "change",
        },
      },
      formItems: [
        { label: "名称", prop: "name", options: "names" },
        { label: "星级", prop: "star", options: "stars" },
        { label: "位置", prop: "direction", options: "directions" },
        { label: "基本属性", prop: "mainProp", options: "mainProps" },
        { label: "赛季", prop: "season", options: "seasons" },
      ],
      myProperties: [],
      data: [],
      importData:'',
    };
  },
  computed:{
    exportData() {
      return JSON.stringify(this.app.dataset.source);
    }
  },
  mounted() {
    this.app.dataset.properties.forEach((prop) => {
      this.rules[prop] = {
        required: true,
        message: "请选择机芯属性与值",
        trigger: "blur",
      };
    });
    this.onSearch();
  },
  methods: {
    onSearch() {
      const { id, name, star, direction, season, mainProp } = this.formData;
      this.data = this.app.dataset.source.filter((v) => {
        if (id) return v.id === id;
        const fName = !name || v.name === name;
        const fStar = !star || v.star === star;
        const fDirection = !direction || v.direction === direction;
        const fSeason = !season || v.season === season;
        const fMainProp = !mainProp || v.mainProp === mainProp;
        return fName && fStar && fDirection && fSeason && fMainProp;
      });
    },
    initEdit(data) {
      this.myProperties = this.app.dataset.properties
        .filter((p) => data[p])
        .map((v) => {
          return {
            prop: v,
          };
        });
      this.formData = { ...data };
    },
    addProp() {
      if (this.myProperties.length >= 4) return;
      this.myProperties.push({ prop: "" });
    },
    removeProp(index) {
      const prop = this.myProperties[index].prop;
      this.$delete(this.formData, prop);
      this.myProperties.splice(index, 1);
    },
    properties(index) {
      let has = this.myProperties
        .filter((v, i) => i !== index)
        .map((v) => v.prop);
      return this.app.dataset.properties.filter((v) => !has.includes(v));
    },
    onPropChange(key, item) {
      if (item.prop) {
        this.$delete(this.formData, item.prop);
      }
      item.prop = key;
    },
    onSave() {
      this.$refs.form
        .validate()
        .then(() => {
          let list = [...this.app.dataset.source];
          if (!this.formData.id) {
            let props = Object.keys(this.formData);
            if (
              list.some((v) =>
                props.every((prop) => this.formData[prop] === v[prop])
              )
            ) {
              return this.$message.warning("不能重复添加机芯");
            }
            list.push({ id: Date.now(), ...this.formData });
          } else {
            let index = list.findIndex((v) => v.id === this.formData.id);
            list[index] = { ...this.formData };
            this.onReset();
          }
          this.$message.success("保存成功");
          storage.updateMovement(list);
          this.app.update();
          this.onSearch();
        })
        .catch(() => {});
    },
    remove(item) {
      this.$confirm("是否删除此机芯?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let list = this.app.dataset.source.filter(
            (v) => v.id !== item.id
          );
          storage.updateMovement(list);
          this.app.update();
          this.onSearch();
        })
        .catch(() => {});
    },
    removeAll() {
      this.$confirm("此操作将删除全部机芯，是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          storage.updateMovement([]);
          this.app.update();
          this.onSearch();
        })
        .catch(() => {});
    },
    onReset() {
      this.formData = {};
      this.myProperties = [];
      this.$nextTick(() => this.$refs.form.clearValidate());
      this.onSearch();
    },
    onImport() {
      if(!this.importData.trim()) return;
      let list = [];
      try {
        list = JSON.parse(this.importData);
      } catch (error) {
        return this.$message.warning('格式有误');
      }
      if(!(list instanceof Array)) {
        return this.$message.warning('格式有误');
      }
      this.$confirm("确定要导入吗?", "提示", {
        type: "warning",
      }).then(() => {
        storage.updateMovement(list);
        this.app.update();
        this.onSearch();
        this.importData = '';
        this.$message.success('导入成功')
      })
    }
  },
}
</script>

<style>

</style>